package AIColorUSAStates;

import java.util.ArrayList;
import java.util.Random;

public class MinConflictAlgorithmus 
{
	private static int countRunTimes = 0;
	private static int countStepsPlateau = 0;
	private static int countIterations = 0;
	
	public static int getAveragePlateauTimes()
	{
		return countStepsPlateau / countRunTimes;
	}
	
	public static int getAverageIterations() {
		return countIterations / countRunTimes;
	}
	
	public static boolean start(int maxSteps)
	{
		countRunTimes++;
			
		// Run Algorithmus
		for (int i = 0; i < maxSteps; i++) 
		{
			int sumCon = getSumConflicts();
			
			if (MinConflictAlgorithmus.isSolution())
			{		
				countIterations += i;
				return true;
			}
			
			// Get Random State with conflicts
			Random ran = new Random();
			Node randomNodeWithConflicts = Graph.allNodesInGraph.get(ran.nextInt(Graph.allNodesInGraph.size()));
			while (randomNodeWithConflicts.getCollisions() == 0) 
			{
				randomNodeWithConflicts = Graph.allNodesInGraph.get(ran.nextInt(Graph.allNodesInGraph.size()));
			}
			
			randomNodeWithConflicts.Color =randomNodeWithConflicts.getColorWithMinimumCollisionen();
			
			// Detect Plateau
			if (sumCon == getSumConflicts())
			{
				countStepsPlateau++;
			}
		}
		
		countIterations += maxSteps;
		return false;
	}
	
	private static int getSumConflicts()
	{
		int sum = 0;
		for (Node node : Graph.allNodesInGraph) 
		{
			sum += node.getCollisions();
		}
		
		return sum;
	}

	private static boolean isSolution()
	{
		return Graph.allNodesInGraph.getMaxCollisions() == 0;
	}

}
